package com.socialrss.viewlisteners;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Toast;

import com.socialrss.R;
import com.socialrss.accounts.AbstractHolder;
import com.socialrss.accounts.FollowedPerson;
import com.socialrss.adapters.SelectTypeClickListener;
import com.socialrss.adapters.StringWithStatus;
import com.socialrss.adapters.SwipeDetector;
import com.socialrss.constants.SocialNetworkNames;
import com.socialrss.constants.SocialNetworkNames.SocialNetKeys;
import com.socialrss.utils.SocialRssModel;

public class ManageConnections extends BaseActivity implements AbstractManageListListener{
	private ListView mainListView ;  
	private ArrayAdapter<FollowedPerson> listAdapter;
	private TextView searchConnTextView;
	private Button commitButton, selectConnTypeButton;
	private ArrayList<FollowedPerson>  connlist;
	private ArrayList<FollowedPerson> listNotOnView;
	private LinkedHashMap<String, ArrayList<FollowedPerson>> allHolders;
	private ArrayList<StringWithStatus> conntype;
	private SelectTypeClickListener socialNetworkSelectListener;
	private SwipeDetector swipelistener;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Generate list View from ArrayList 
		setContentView(R.layout.manage_connections);
		
	    //now initialize a hash map to categorize all holders depending on their social network
	    allHolders = new LinkedHashMap<String, ArrayList<FollowedPerson>>(5);
		
	    //initialize list options
	    conntype = new ArrayList<StringWithStatus>(5);
	    conntype.add(new StringWithStatus(SocialNetworkNames.FACEBOOK, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.TWITTER, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.GOOGLE, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.INSTAGRAM, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.CATEGORY, true));;
	    
	    //Initialize properties   
	    mainListView = (ListView) findViewById( R.id.mc_connectionlist );  
	    
	    //Configure connlist for ConnectionAdapter
	    this.configureConnListForAdapter();
	    
	    
	    // Create ConnectionAdapter for mainListView  
	    listAdapter = new ConnectionAdapter(this,R.layout.connection_list_item, connlist);
	    mainListView.setAdapter( listAdapter );
	    mainListView.setClickable(false);
	    
	    //add listeners
	    //addSwipeListenerToListView();
		addListenerOnSearchConnTextView();
		addListenerToFinishButton();
		addListenerToSelectConnTypeButton();
		addListenerToAddConnButton();
	}
	public void addSwipeListenerToListView(){
		swipelistener = new SwipeDetector();
	    mainListView.setOnTouchListener(swipelistener);
		mainListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(swipelistener.swipeDetected()){
					AbstractHolder temp = (AbstractHolder)mainListView.getItemAtPosition(arg2);
					Toast.makeText(ManageConnections.this, "Left to right for " + temp.getName(), Toast.LENGTH_LONG).show();
				}
				return false;
			}
		});
	}
	public void addListenerToFinishButton(){
		commitButton = (Button) findViewById(R.id.mc_addConnCommitButton);
		commitButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Back to main activity
				Intent i = new Intent(ManageConnections.this, MainActivity.class);
				startActivity(i);
				
			}
		});
	}
	public void addListenerToAddConnButton(){
		View addNewConnButton = findViewById(R.id.mc_addConnBut);
		addNewConnButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(ManageConnections.this, AddConnectionFromSocialNetwork.class);
				startActivity(i);
				
			}
		});
	}
	public void addListenerToSelectConnTypeButton(){
		selectConnTypeButton = (Button) findViewById(R.id.mc_selectConnTypeButton);
		socialNetworkSelectListener = new SelectTypeClickListener((Context)this,
				(LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE), conntype, R.id.mc_searchEditText);
		selectConnTypeButton.setOnClickListener(socialNetworkSelectListener);
	}
	public void addListenerOnSearchConnTextView(){
		searchConnTextView = (TextView) findViewById(R.id.mc_searchEditText);
		searchConnTextView.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				int listNotOnViewsize = listNotOnView.size();
				int connlistsize = connlist.size();
				
				for(int i= 0; i < connlistsize; i++){
					if(!connlist.get(i).connNameContains(s.toString())){
						listNotOnView.add(connlist.remove(i));
						i--;
						connlistsize--;
					}
				}
				for(int i=0; i < listNotOnViewsize; i++){
					if(listNotOnView.get(i).connNameContains(s.toString())){
						connlist.add(listNotOnView.remove(i));
						i--;
						listNotOnViewsize--;
					}
				}
				((ConnectionAdapter) listAdapter).updateList(connlist);
				listAdapter.notifyDataSetChanged();
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {				
			}
			
			@Override
			public void afterTextChanged(Editable s) {				
			}
		});
	}
	private void configureConnListForAdapter(){
		// Create and populate a List of planet names.
	    listNotOnView = new ArrayList<FollowedPerson>();
	    connlist = new ArrayList<FollowedPerson> (4);
	    
	    connlist.addAll(SocialRssModel.Instance(this).allConnections());
	}
	public void adjustButtonListener_setConnList(){
		boolean allSocialNetworksAreSelected = true;
		for(int i=0; i<conntype.size(); i++){
			if(!conntype.get(i).getStatus())
				allSocialNetworksAreSelected = false;
		}
		if(allSocialNetworksAreSelected){		//if all of them are selected
			connlist.removeAll(connlist);
			connlist.addAll(SocialRssModel.Instance(null).allConnections());
		}
		else{									//if some of them are selected
			connlist.removeAll(connlist);
			for(int i=0; i<4;i++){
				StringWithStatus temp = conntype.get(i);
				if(temp.getStatus()){			//if this conntype is selected
					if(allHolders.containsKey(temp.getName())){				//if it is already in linked hash map, directly insert it from there
						connlist.addAll(allHolders.get(temp.getName()));
					}
					else{													//if it is not in linked hash map
						Iterator<AbstractHolder> iter = SocialRssModel.Instance(null).socialNetworksWithConnections().get(temp.getName()).values().iterator();
						ArrayList<FollowedPerson> tempList = new ArrayList<FollowedPerson>();		
						while(iter.hasNext()){								//take all connections in selected social network
							tempList.add((FollowedPerson) iter.next());
						}
						allHolders.put(temp.getName(), tempList);			//put them all into hash map with a key which is the name of social network
						connlist.addAll(tempList);							//also put them into connlist which are used by listview
					}
				}
			}
		}
		((ConnectionAdapter) listAdapter).updateList(connlist);
		listAdapter.notifyDataSetChanged();
	}
	private class ConnectionAdapter extends ArrayAdapter<FollowedPerson> {
		 
		  private ArrayList<FollowedPerson>  connectionList;
		 
		  public ConnectionAdapter(Context context, int textViewResourceId, ArrayList<FollowedPerson>  connList) {
			  super(context, textViewResourceId, connList);
			  this.connectionList = connList;
		  }
		  public void updateList(ArrayList<FollowedPerson>  connList){
			  connectionList = connList;
		  }
		  private class ViewHolder {
			  TextView name;
			  ImageView icon;
		  }
		  
		  
		  
		  @Override
		  public View getView(int position, View convertView, ViewGroup parent) {

			  ViewHolder holder = null;
			  Log.v("ConvertView", String.valueOf(position));
		 
			  if (convertView == null) {
				  LayoutInflater vi = (LayoutInflater)(((Activity)this.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
				  convertView = vi.inflate(R.layout.connection_list_item, null);
			 
				  holder = new ViewHolder();
				  holder.name = (TextView) convertView.findViewById(R.id.cli_connName);
				  holder.icon = (ImageView) convertView.findViewById(R.id.cli_socialImage);
				  convertView.setTag(holder);
			  } 
			  else {
				  holder = (ViewHolder) convertView.getTag();
			  }
		 
			  final FollowedPerson conn = connectionList.get(position);
			  holder.name.setText(conn.getName());				//set list item name
			  SocialNetKeys socialN = conn.getConntype();		//set list item icon
			  switch(socialN){
			  	case fa:
			  		holder.icon.setImageResource(R.drawable.facebook_icon);
			  		break;
			  	case g_:
			  		holder.icon.setImageResource(R.drawable.google_plus_icon);
			  		break;
			  	case group:
			  		holder.icon.setImageResource(R.drawable.group_icon);
			  		break;
			  	case tw:
			  		holder.icon.setImageResource(R.drawable.twitter_icon);
			  		break;
			  	case ins:
			  		holder.icon.setImageResource(R.drawable.instagram_icon);
			  		break;
			  	case f_sq:
			  		holder.icon.setImageResource(R.drawable.google_plus_icon);
			  		break;
			  }
			  return convertView;
		 
		  }
	}
}
